package com.cloudpark.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.cloudpark.common.util.CommonUtil;
import com.cloudpark.common.util.Constants;
import com.cloudpark.common.util.JsonUtil;
import com.cloudpark.common.util.MessageUtil;
import com.cloudpark.common.util.ObjectUtil;
import com.cloudpark.common.util.Pagination;
import com.cloudpark.model.entity.AdminUser;
import com.cloudpark.model.entity.Estate;
import com.cloudpark.model.entity.EstateWechat;
import com.cloudpark.service.EstateService;

@Controller
@RequestMapping("/estate")
public class EstateController extends BaseController {

    private static final Logger log = Logger.getLogger(EstateController.class);

    @Autowired
    private EstateService estateService;

    @RequestMapping(value = "/data", method = RequestMethod.GET)
    public ModelAndView myestate(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("estate/data.jsp");
        initMenu(request, response);
        return mv;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView list(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("estate/list.jsp");
        initMenu(request, response);
        return mv;
    }

    @RequestMapping(value = "/queryEstateList", method = RequestMethod.POST)
    @ResponseBody
    public String queryEstateList(HttpServletRequest request,
            @RequestParam(value = "start", defaultValue = "0") int start,
            @RequestParam(value = "length", defaultValue = "10") int length, @RequestParam(value = "draw") int draw,
            HttpServletResponse response) {
        String result = "";
        try {
            AdminUser adminUser = isSessionExpire(request, response);
            String name = request.getParameter("name");
            String tel = request.getParameter("tel");
            Map<String, String> params = new HashMap<String, String>();
            if (StringUtils.isNotEmpty(name)) {
                params.put("name", name);
            }
            if (StringUtils.isNotEmpty(tel)) {
                params.put("tel", tel);
            }
            Pagination page = estateService.queryEstateList(params, start, length, adminUser.getEstateId());
            result = JsonUtil.toJSONDataTables(page, draw);
        } catch (Exception e) {
            log.error("query estate list error :", e);
            result = MessageUtil.error("服务器忙!");
        }
        return result;
    }

    @RequestMapping(value = "/editEstate", method = RequestMethod.GET)
    public ModelAndView editEstate(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("estate/editEstate.jsp");
        initMenu(request, response);
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            Estate estate = estateService.queryEstateById(Long.valueOf(id));
            if (StringUtils.isNotBlank(estate.getContractPic())) {
                estate.setContractPic(Constants.imagesUrl+estate.getContractPic());
            }
            if (StringUtils.isNotBlank(estate.getLogo())) {
                estate.setLogo(Constants.imagesUrl+estate.getLogo());
            }
            mv.addObject("estate", estate);
            mv.addObject("isUpdate", 1);
        } else {
            mv.addObject("isUpdate", 0);
        }
        return mv;
    }

    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView saveOrUpdate(HttpServletRequest request, HttpServletResponse response) {
        initMenu(request, response);
        ModelAndView mv = new ModelAndView("estate/editEstate.jsp");
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String legalPerson = request.getParameter("legalPerson");
        String cardNo = request.getParameter("cardNo");
        String tel = request.getParameter("tel");
        String owner = request.getParameter("owner");
        String dueBank = request.getParameter("dueBank");
        String subbranch = request.getParameter("subbranch");
        String account = request.getParameter("account");
        String prov = request.getParameter("prov");
        String city = request.getParameter("city");
        String flag = request.getParameter("flag");

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile contractPicFile = multipartRequest.getFile("contractPicFile");
        MultipartFile logoFile = multipartRequest.getFile("logoFile");

        try {
            Estate estate = null;
            if (StringUtils.isNotEmpty(id)) {
                estate = estateService.queryEstateById(Long.valueOf(id));
                mv.addObject("isUpdate", 1);
            } else {
                estate = new Estate();
                mv.addObject("isUpdate", 0);
                estate.setCreatedTime(new Date());
            }
            estate.setName(name);
            estate.setLegalPerson(legalPerson);
            estate.setCardNo(cardNo);
            estate.setTel(tel);
            estate.setOwner(owner);
            estate.setDueBank(dueBank);
            estate.setSubbranch(subbranch);
            estate.setAccount(account);
            estate.setProv(prov);
            estate.setCity(city);
            estate.setFlag(flag);

            // 合同
            if (null != contractPicFile && StringUtils.isNotEmpty(contractPicFile.getOriginalFilename())) {
                String weburl = request.getSession().getServletContext().getRealPath(""); // 宸ョ▼鍚嶅悗娌℃湁鏂滅嚎
                weburl = weburl.substring(0, weburl.lastIndexOf(Constants.PREFIX_SLASH_ESCAPED));
                weburl = weburl + Constants.PREFIX_SLASH + Constants.UPLOAD_IMAGES_DIR;

                File DIR = new File(weburl);
                if (!DIR.exists())
                    DIR.mkdirs();

                String suffix = contractPicFile.getOriginalFilename().substring(contractPicFile.getOriginalFilename().lastIndexOf("."));
                String fileName = CommonUtil.getRandomString(20) + suffix;

                String fileUrl = weburl + Constants.PREFIX_SLASH + fileName;
                File file = new File(fileUrl);
                contractPicFile.transferTo(file);
                estate.setContractPic(fileName);
            }

            // logo
            if (null != logoFile && StringUtils.isNotEmpty(logoFile.getOriginalFilename())) {
                String weburl = request.getSession().getServletContext().getRealPath(""); // 宸ョ▼鍚嶅悗娌℃湁鏂滅嚎
                weburl = weburl.substring(0, weburl.lastIndexOf(Constants.PREFIX_SLASH_ESCAPED));
                weburl = weburl + Constants.PREFIX_SLASH + Constants.UPLOAD_IMAGES_DIR;

                File DIR = new File(weburl);
                if (!DIR.exists())
                    DIR.mkdirs();

                String suffix = logoFile.getOriginalFilename().substring(logoFile.getOriginalFilename().lastIndexOf("."));
                String fileName = CommonUtil.getRandomString(20) + suffix;

                String fileUrl = weburl + Constants.PREFIX_SLASH + fileName;
                File file = new File(fileUrl);
                logoFile.transferTo(file);
                estate.setLogo(fileName);
            }
            estateService.saveOrUpdate(estate);
            if (StringUtils.isNotBlank(estate.getContractPic())) {
                estate.setContractPic(Constants.imagesUrl+estate.getContractPic());
            }
            if (StringUtils.isNotBlank(estate.getLogo())) {
                estate.setLogo(Constants.imagesUrl+estate.getLogo());
            }
            mv.addObject("estate", estate);
            mv.addObject("message", "编辑物业信息成功!");
            mv.addObject("saveOk", "1");
        } catch (Exception e) {
            log.error("编辑物业信息失败", e);
            mv.addObject("message", "编辑物业信息失败!");
            mv.addObject("saveOk", "2");
        }
        return mv;
    }
    
    @RequestMapping(value = "/editEstateWechat", method = RequestMethod.GET)
    public ModelAndView editEstateWechat(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("estate/editEstateWechat.jsp");
        initMenu(request, response);
        String estateId = request.getParameter("estateId");
        EstateWechat estateWechat = estateService.queryEstateWechatByEstateId(Long.valueOf(estateId));
        mv.addObject("estateWechat", estateWechat);
        if (null != estateWechat) {
            mv.addObject("isUpdate", 1);
        } else {
            mv.addObject("isUpdate", 0);
        }
        mv.addObject("estateId", estateId);
        return mv;
    }
    
    @RequestMapping(value = "/saveOrUpdateWechat", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView saveOrUpdateWechat(HttpServletRequest request, HttpServletResponse response) {
        initMenu(request, response);
        ModelAndView mv = new ModelAndView("estate/editEstateWechat.jsp");
        String estateId = request.getParameter("estateId");
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String developerId = request.getParameter("developerId");
        String mchId = request.getParameter("mchId");
        String token = request.getParameter("token");
        String appId = request.getParameter("appId");
        String appSecret = request.getParameter("appSecret");
        String keySecret = request.getParameter("keySecret");

        try {
            EstateWechat estateWechat = null;
            if (ObjectUtil.isNotBlank(id)) {
            	estateWechat = estateService.queryEstateWechatById(Long.valueOf(id));
                mv.addObject("isUpdate", 1);
            } else {
            	estateWechat = new EstateWechat();
                mv.addObject("isUpdate", 0);
            }
            estateWechat.setEstateId(Long.valueOf(estateId));
            estateWechat.setName(name);
            estateWechat.setDeveloperId(developerId);
            estateWechat.setMchId(mchId);
            estateWechat.setToken(token);
            estateWechat.setAppId(appId);
            estateWechat.setAppSecret(appSecret);
            estateWechat.setKeySecret(keySecret);
            estateService.saveOrUpdateWechat(estateWechat);
            mv.addObject("estateWechat", estateWechat);
            mv.addObject("message", "编辑物业公众号信息成功!");
            mv.addObject("saveOk", "1");
        } catch (Exception e) {
            log.error("编辑物业公众号信息失败", e);
            mv.addObject("message", "编辑物业公众号信息失败!");
            mv.addObject("saveOk", "2");
        }
        return mv;
    }

}
